package com.koocloud.electroplatemanage.service.impl;

import cn.hutool.core.lang.Validator;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.koocloud.electroplatemanage.auth.mapper.IUserDao;
import com.koocloud.electroplatemanage.common.pojo.ResponseTemplate;
import com.koocloud.electroplatemanage.mapper.MainProductionMapper;
import com.koocloud.electroplatemanage.mapper.ProcessCheckMapper;
import com.koocloud.electroplatemanage.mapper.ProcessMapper;
import com.koocloud.electroplatemanage.pojo.*;
import com.koocloud.electroplatemanage.pojo.mainpojo.WIP;
import com.koocloud.electroplatemanage.service.InspectService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.List;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

import static com.koocloud.electroplatemanage.constant.MainWIPRouteConstant.*;

/**
 * @program: Information_platform
 * @description: 工艺卡片检验实现层
 * @author: xxc
 * @create: 2020-11-17 09:27
 */
@Service
@Transactional(rollbackFor=Exception.class)
public class InspectServiceImpl implements InspectService {
    @Resource
    private IUserDao iUserDao;

    @Resource
    private ProcessCheckMapper processCheckMapper;
    @Resource
    private MainProductionMapper mainProductionMapper;
    Lock lock=new ReentrantLock();

    /**
     *@Description: 通过工单号查询一条记录
     *@Param: [workOrderNumber]
     *@return: com.koocloud.electroplatemanage.common.pojo.ResponseTemplate
     *@Author: xxc
     *@date: 2020/11/17
     */
    @Override
    public ResponseTemplate selectByWorkOrderNumber(String workOrderNumber) {
        try {
            ProcessCheck processCheck = processCheckMapper.selectByWorkOrderNumber(workOrderNumber);
            //判断查表操作是否成功
            if (null != processCheck) {
                //查表成功返回数据
                return ResponseTemplate.builder().code(0).message("查询成功").count(1l).data(processCheck).build();
            } else {
                //查表失败返回提示
                return ResponseTemplate.builder().code(1).message("没有此数据").count(0l).build();
            }
        } catch (Exception e) {
            //遇到异常，返回异常原因
            e.printStackTrace();
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return ResponseTemplate.builder().code(1).message(e.getMessage()).count(0l).build();
        }

    }

    /**
     *@Description: 全表查询
     *@Param: [page, limit, processCheck]
     *@return: com.koocloud.electroplatemanage.common.pojo.ResponseTemplate
     *@Author: xxc
     *@date: 2020/11/17
     */
    @Override
    public ResponseTemplate selectAllData(String page, String limit, ProcessCheck processCheck) {
        //校验分页参数是否为纯数字 并且page和limit不都等于0
        if(Validator.isNumber(page)&&Validator.isNumber(limit)&&!("0".equals(page)&&"0".equals(limit))) {
            try {
                lock.lock();
                int rows = -1;
                //开始查询在工表，状态为5的插入来料基本信息
                List<WIP> wipList= mainProductionMapper.selectAllWIPByLocation(CHECK);
                if(!StringUtils.isEmpty(wipList)) {
                    for(WIP wip:wipList) {
                        //获取工单号
                        if(!StringUtils.isEmpty(wip.getWorkOrderNumber())) {
                            //数据库重复工单号校验
                            int count = processCheckMapper.selectWorkOrderNumberCount(wip.getWorkOrderNumber());
                            if(count>0) {
                                continue;
                            }


                            ProcessCheck insertProcessCheck = new ProcessCheck();
                            if(!StringUtils.isEmpty(wip.getEntryPerson())) {
                                //设置创建人
                                insertProcessCheck.setCreator(wip.getEntryPerson());
                            }
                            if(!StringUtils.isEmpty(wip.getEntryTime())) {
                                //设置创建时间
                                insertProcessCheck.setCreateTime(wip.getEntryTime());
                            }
                            String workOrderNumber = wip.getWorkOrderNumber();
                            //设置工单号
                            insertProcessCheck.setWorkOrderNumber(workOrderNumber);
                            insertProcessCheck.setDeleteFlag("1");
                                rows=processCheckMapper.insert(insertProcessCheck);
                                //记录成功插入条数
                            }

                        }
                    }

                //在工表插入完成后开始查询
                if(StringUtils.isEmpty(wipList)||(wipList.size()>0&&rows>0)||(wipList.size()>=0&&rows==-1)) {
                //开始分页
                PageHelper.startPage(Integer.valueOf(page), Integer.valueOf(limit));
                //全局查询
                List<ProcessCheck> ProcessCheckList = processCheckMapper.selectAllData(processCheck);
                //构造分页实体
                PageInfo<ProcessCheck> info=new PageInfo<>(ProcessCheckList);
                if (info.getTotal()>0) {
                    //查询到数据
                    return ResponseTemplate.builder().code(0).message("查询成功").count(info.getTotal()).data(info.getList()).build();
                } else {
                    //没有查询到数据
                    return ResponseTemplate.builder().code(1).message("没有查到对应数据").count(0l).build();
                }
               }

                else {
                    return ResponseTemplate.builder().code(1).message("在工表数据导入失败").count(0l).build();
                }
            } catch (Exception e) {
                //遇到异常，返回异常原因
                e.printStackTrace();
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                return ResponseTemplate.builder().code(1).message(e.getMessage()).count(0l).build();
            }
            finally {
                lock.unlock();
            }
        } else {
            return ResponseTemplate.builder().code(1).message("分页参数错误").count(0l).build();
        }

    }

    /**
     *@Description: 新增一条数据
     *@Param: [processCheck, userId]
     *@return: com.koocloud.electroplatemanage.common.pojo.ResponseTemplate
     *@Author: xxc
     *@date: 2020/11/17
     */
    @Override
    public ResponseTemplate insert(ProcessCheck processCheck, String userId) {
        try{
            lock.lock();
            //获取创建人
            User user = iUserDao.selectByPk(userId);
            //设置创建人
            processCheck.setCreator(user.getJobNum());
            //插入一条记录
            int row = processCheckMapper.insert(processCheck);

            if (row > 0) {
                return ResponseTemplate.builder().code(0).message("插入数据成功").count(1l).build();
            } else {//没有异常并且插入数据失败，原则上不出现
                return ResponseTemplate.builder().code(1).message("插入数据失败").count(0l).build();
            }
        } catch (Exception e) {
            //出现异常返回异常原因
            e.printStackTrace();
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return ResponseTemplate.builder().code(1).message(e.getMessage()).count(0l).build();
        }
        finally {
            lock.unlock();
        }

    }

    /**
     *@Description: 逻辑删除一条记录
     *@Param: [id, userId, deleteFlag]
     *@return: com.koocloud.electroplatemanage.common.pojo.ResponseTemplate
     *@Author: xxc
     *@date: 2020/11/17
     */
    @Override
    public ResponseTemplate delete(String id, String userId, String deleteFlag) {
        try {
            lock.lock();
            //获取修改人
            User user = iUserDao.selectByPk(userId);
            //逻辑删除一条记录
            int rows = processCheckMapper.delete(id,user.getJobNum(),deleteFlag);
            //判断删除操作是否成功
            if (rows > 0) {
                //删除成功返回数据
                return ResponseTemplate.builder().code(0).message("删除成功").count(1l).build();
            } else {
                //删除失败返回提示
                return ResponseTemplate.builder().code(1).message("删除失败").count(0l).build();
            }
        } catch (Exception e) {
            //遇到异常，返回异常原因
            e.printStackTrace();
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return ResponseTemplate.builder().code(1).message(e.getMessage()).count(0l).build();
        }
        finally {
            lock.unlock();
        }

    }

    /**
     *@Description: 修改一条记录
     *@Param: [processCheck, userId]
     *@return: com.koocloud.electroplatemanage.common.pojo.ResponseTemplate
     *@Author: xxc
     *@date: 2020/11/17
     */
    @Override
    public ResponseTemplate update(ProcessCheck processCheck, String userId) {
        try {
            lock.lock();
            //获取修改人
            User user = iUserDao.selectByPk(userId);
            //设置修改人
            processCheck.setModifier(user.getJobNum());
            //没有异常并且修改数据条数大于0
            int row = processCheckMapper.update(processCheck);
            if(row > 0) {
                return ResponseTemplate.builder().code(0).message("修改数据成功").count(1l).build();
            }
            else {//没有异常并且修改数据失败，原则上不出现
                return ResponseTemplate.builder().code(1).message("修改数据失败").count(0l).build();
            }
        } catch (Exception e) {
            //出现异常返回异常原因
            e.printStackTrace();
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return ResponseTemplate.builder().code(1).message(e.getMessage()).count(0l).build();
        }
        finally {
            lock.unlock();
        }

    }

    /**
     *@Description: 检验确认
     *@Param: [workOrderNumber]
     *@return: com.koocloud.electroplatemanage.common.pojo.ResponseTemplate
     *@Author: xxc
     *@date: 2020/11/20
     */
    @Override
    public ResponseTemplate confirmEntryInfo(String workOrderNumber, String userId) {
        try{
            lock.lock();
            //改变检验状态
            processCheckMapper.changeState(workOrderNumber);
            return ResponseTemplate.builder().code(0).message("确认成功").count(1l).build();
        } catch (Exception e) {
            //出现异常返回异常原因
            e.printStackTrace();
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return ResponseTemplate.builder().code(1).message(e.getMessage()).count(0l).build();
        }
        finally {
            lock.unlock();
        }
    }
}
